package telcoGUI.actionListener;

import java.awt.event.ActionEvent;

import swa2012.telco.broker.beans.Client;
import swa2012.telco.broker.beans.Provider;
import telcoClient.client.TelcoClient;
import telcoClient.common.TelcoInitializationException;
import telcoGUI.messageHandler.TelcoGUIMessageHandler;
import telcoGUI.userInterface.ProviderBean;
import telcoGUI.userInterface.TelcoClientGUI;

public class ConnectButtonListener extends TelcoActionListener
{
	public ConnectButtonListener(TelcoClientGUI telcoGUI)
	{
		super(telcoGUI);
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0)
	{
		String id = this.telcoGUI.getClientIDTextField().getText();
		ProviderBean selectedProvider = (ProviderBean) this.telcoGUI.getProviderComboBox().getSelectedItem();
		String endpoint = selectedProvider.getUri();
		
		try {
			if (this.telcoGUI.getTelcoClient() != null)
				this.telcoGUI.getTelcoClient().disconnectFromProvider();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			TelcoClient newClient = new TelcoClient(id, endpoint, new TelcoGUIMessageHandler(this.telcoGUI));
			this.telcoGUI.setTelcoClient(newClient);
			
			Client c = newClient.getClient();
			System.out.println("client.ID: " + c.getID());
			System.out.println("client.provider: " + c.getProvider());
			System.out.println("client.provider.ID: " + c.getProvider().getID());
			
			assert c.getID() != null;
			assert !c.getID().isEmpty();
			assert c.getProvider() != null;

			Provider p = c.getProvider();
			assert p.getID() != null;
			assert p.getBrokerCallbackEndpoint() != null;
			assert !p.getID().isEmpty();
		}
		
		catch (TelcoInitializationException e) {
			e.printStackTrace();
		}
	}
}
